﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2013.Setup.Utilities;

namespace ServBus.ListForm2013.Setup.Commands
{
    class RetractSolutionCmd : BaseCommand
    {
        public override bool AllowRollback
        {
            get
            {
                return false;
            }
        }

        private bool IsLocalDeploy()
        {
            return ((SPServer.LocalServerRole == SPServerRole.SingleServer) ||
                (SPFarm.Local.TimerService.Instances.Count == 1));
        }

        public override string Description
        {
            get { return Properties.Resources.CmdRetractSolution; }
        }

        public override bool Execute()
        {
            try
            {
                Log.WriteLog(Log.LogType.Info, "Starting Retracting Solution...");
                SPSolution solution = SPFarm.Local.Solutions[Constants.WSPNAME];
                Collection<SPWebApplication> webapps = new Collection<SPWebApplication>();
                foreach (SPWebApplication webapp in solution.DeployedWebApplications)
                    webapps.Add(webapp);
                if (webapps.Count > 0)
                {
                    if (IsLocalDeploy())
                    {
                        solution.RetractLocal(webapps);
                    }
                    else
                    {
                        solution.Retract(DateTime.Now.AddHours(-1), webapps);
                    }

                    Log.WriteLog(Log.LogType.Info, "Solution Retracted.");
                }
                else
                {
                    Log.WriteLog(Log.LogType.Info, "Solution has not been deployed yet.");
                }
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteLog(Log.LogType.Error, "Retract Solution Error. " + ex.GetType().FullName + ". " + ex.Message);
                return false;
            }
        }

        public override bool Rollback()
        {
            return true;
        }
    }
}
